#include "vpclock.h"
extern "C"
{
#include "libavutil/time.h"
#include "libavutil/avutil.h"
}
VpClock::VpClock()
{
    m_pause = false;
    m_speed = 1.0;
    set_clock(AV_NOPTS_VALUE, 0);
}

void VpClock::set_clock(double pts, int serial)
{
    double time = av_gettime_relative() / 1000000.0;
    set_clock_at(pts, serial, time);
}

void VpClock::set_clock_at(double pts, int serial, double time)
{
    m_pts          = pts;
    m_last_updated = time;
    m_pts_drift    = pts - time;
    m_serial       = serial;
}

void VpClock::set_clock_speed(double speed)
{
    set_clock(get_clock(), m_serial);
    m_speed = speed;
}

double VpClock::get_clock()
{
    if(m_pause) {
        return m_pts;
    } else {
        double time = av_gettime_relative() / 1000000.0;
        return m_pts_drift + time - ( time - m_last_updated ) * (1.0 - m_speed);
    }
}
